$(function () {
    const $image = $('.upload-image')
    const options = {
        aspectRatio: 1,
        preview: '.pre1, .pre2'
    }
    $image.cropper(options)

    $('#select-file').on('click', function () {
        $('#file').click()
    })

    $('#file').on('change', function () {
        const file = this.files[0]
        const src = window.URL.createObjectURL(file)
        $image.cropper('destroy').attr('src', src).cropper(options)
    })

    $('#upload-file').on('click', function () {
        if($('#file')[0].files.length <= 0){
            layui.layer.msg('请上传图片')
        }
        const BASE_64 = $image.cropper('getCroppedCanvas', {
            width: 100,
            height: 100
        }).toDataURL('image/png')
        $.post('/my/update/avatar', {avatar: BASE_64}).then(res => {
            if(res.status !== 1){
                layui.layer.msg('上传失败')
            }
            layui.layer.msg('上传成功')
            parent.initUserInfo()
        })
    })
})